package data

import (
	_ "embed"
	"encoding/json"
	"log"
	"math/rand"
	"time"
)

type WordKey struct {
	Title string `json:"title"` //标题
	Hint  string `json:"hint"`  //提示
	Len   string `json:"len"`   //长度
}

func (w *WordKey) Marshal() string {
	marshal, _ := json.Marshal(*w)
	return string(marshal)
}

//go:embed handle_data.json
var jsonFileData string
var previousIndex int

var wordData []WordKey = make([]WordKey, 0)

func init() {
	err := json.Unmarshal([]byte(jsonFileData), &wordData)
	//加载错误
	if err != nil {
		log.Panicf("加载题库失败：%s", err.Error())
	}
}

// GetKey 获取当前题目
func GetKey() *WordKey {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for {
		index := r.Intn(len(wordData))
		//不能与上次题目相同
		if index == previousIndex {
			continue
		}
		previousIndex = index
		word := wordData[index]
		log.Println("当前的key为：", word)
		return &word
	}
}
